package com.zou.lotterylucky.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.jakewharton.rxbinding3.view.clicks
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction
import com.v2.request.RequestCenter
import com.v2.utils.okhttp.OkHttpRequestCallback
import com.zou.lotterylucky.Constants
import com.zou.lotterylucky.R
import com.zou.lotterylucky.adapters.BetsListAdapter
import com.zou.lotterylucky.data.Order
import com.zou.lotterylucky.utils.TLog
import kotlinx.android.synthetic.main.activity_deal_detail.*
import org.json.JSONException
import org.json.JSONObject
import java.text.DecimalFormat
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 订单详情界面
 */
class OrderDetailActivity : BaseActivity() {
    lateinit var order: Order
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            setResult(RESULT_OK)
            finish()
        }
    }

    @SuppressLint("CheckResult", "SetTextI18n", "ResourceAsColor")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_deal_detail)

        topbar.setTitle(getString(R.string.dingdanxiangqing))
        topbar.addLeftBackImageButton().setOnClickListener { onBackPressed() }
        order = selectedOrder
        textOrder.text = order.serialNumber
        textTime.text = getString(R.string.xiadanshijian_dot) + order.timeStrAuto + " Wifi"
        textBelong.text = getString(R.string.diqudot) + order.belongTo

        if (order.isWinner == 1) {
            textPrize.text =
                getString(R.string.prize) + DecimalFormat("0.00").format(order.winningAmount)

            if (intent.getIntExtra("from", -1) == 0) {
                btnDelete.visibility = View.GONE
            } else {
                btnDelete.visibility = View.VISIBLE
            }

            if (order.isPaid == 1) {
                btnDelete.text = getString(R.string.paid)
                btnDelete.isEnabled = false
                btnDelete.setBackgroundColor(R.color.kprogresshud_grey_color)
            } else {
                btnDelete.text = getString(R.string.redeem)
            }
        } else {
            if (intent.getIntExtra("from", -1) == 1) {
                btnDelete.text = getString(R.string.no_prize_number)
                btnDelete.isEnabled = false
                btnDelete.setBackgroundColor(R.color.kprogresshud_grey_color)
            } else {
                textPrize.visibility = View.GONE
                text2.visibility = View.GONE

                btnDelete.visibility = View.VISIBLE
                btnXiaDan.text = getString(R.string.xiugai)
            }
        }

        rcv.layoutManager = LinearLayoutManager(this)
        rcv.adapter = BetsListAdapter(order.bets)

        btnXiaDan.clicks().throttleFirst(1000, TimeUnit.MILLISECONDS)
            .subscribe {
                val editBelongTo = editTimeLimit(order.belongTo)
                if (editBelongTo.isNotEmpty()) {
                    selectedOrder.belongTo = editBelongTo
                    val intent = Intent(this@OrderDetailActivity, MainActivity::class.java)
                    intent.putExtra("Modify", true)
                    startActivityForResult(intent, 0)
                }
            }

        btnDelete.setOnClickListener {
            if (order.isWinner == 1) {
                payOrder()
            } /*else {
                if (deleteTimeLimit(order)) {
                    QMUIDialog.MessageDialogBuilder(this)
                        .setTitle(getString(R.string.tishi))
                        .setMessage(getString(R.string.confirm_delete))
                        .addAction(getString(R.string.cancel)) { dialog, _ -> dialog.dismiss() }
                        .addAction(
                            0, getString(R.string.delete), QMUIDialogAction.ACTION_PROP_NEGATIVE
                        ) { dialog, _ ->
//                            val requestQueue = Volley.newRequestQueue(this)
//
//                            val url = Constants.SERVER_URL + "deleteOrder"
//                            val params = JSONObject()
//                            params.put("order_id", order.id)

                            RequestCenter.deleteOrderById(order.id.toString(), object : OkHttpRequestCallback {
                                override fun onSuccess(response: String?) {
                                    allOrders.remove(order)
                                    Toast.makeText(
                                        this@OrderDetailActivity,
                                        getString(R.string.delete_success),
                                        Toast.LENGTH_SHORT
                                    ).show()
                                    dialog.dismiss()
                                    finish()
                                }

                                override fun onFailure(error: String?) {
                                    TLog.net("deleteOrderById() failure:$error")
                                }
                            })

//                            val request = JsonObjectRequest(Request.Method.POST, url, params, {
//                                val status = it.get("status") as Int
//                                if (status == 200) {
//                                    allOrders.remove(order)
//                                    Toast.makeText(
//                                        this,
//                                        getString(R.string.delete_success),
//                                        Toast.LENGTH_SHORT
//                                    ).show()
//                                    dialog.dismiss()
//                                    finish()
//                                }
//                            }, { error ->
//                                error.printStackTrace()
//                            })
//                            requestQueue?.add(request)
                        }
                        .create().show()
                }
            }*/
        }

        textBetsCount.text =
            "${getString(R.string.dingdanshu_dot)}${order.bets.size * order.getRegionCounts()}"
        textMoneyCount.text =
            "${getString(R.string.jine_dot)}${DecimalFormat("0.00").format(order.getTotal())}"
    }

    @SuppressLint("ResourceAsColor")
    private fun payOrder() {
//        val requestQueue = Volley.newRequestQueue(this)
//
//        val url = Constants.SERVER_URL + "saveOrderPaymentStatus"
//        val params = JSONObject()
//        params.put("order_id", order.id.toString())

        RequestCenter.updateOrderPaid(order.id.toString(), object : OkHttpRequestCallback {
            override fun onSuccess(response: String?) {
                order.isPaid = 1
                btnDelete.isEnabled = false
                btnDelete.setBackgroundColor(R.color.kprogresshud_grey_color)
            }

            override fun onFailure(error: String?) {
                TLog.net("updateOrderPaid() failure:$error")
            }
        })

//        val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
//            try {
//
//                val status = response.get("status") as Int
//                if (status == 200 && !response.isNull("data")) {
//                    order.isPaid = 1
//                    btnDelete.isEnabled = false
//                    btnDelete.setBackgroundColor(R.color.kprogresshud_grey_color)
//                }
//
//            } catch (e: JSONException) {
//                e.printStackTrace()
//            }
//        }, { error -> error.printStackTrace() })
//
//        requestQueue?.add(request)
    }

}
